package P046_EqualsNull;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * equals 应考虑null值情景
 *
 * @author xufy1
 */
public class EqualsNull {

    @Test
    public void test2() {
        Person p1 = new Person("张三");
        Person p2 = new Person(null);

        List<Person> list = new ArrayList<Person>();
        list.add(p1);
        list.add(p2);
        System.out.println("值判断 : " + p1.equals(p1));
        System.out.println("值判断 : " + p2.equals(p2));
//        System.out.println("列表中是否包含张三："+list.contains(p1));
//        System.out.println("列表中是否包含张三："+list.contains(p2));
    }
}

class Person {

    private String name;

    public Person(String _name) {
        name = _name;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Person) {
            Person p = (Person) obj;
//            return name.equalsIgnoreCase(p.getName());
            if (p.getName() == null || name == null) {
                return false;
            } else {
                return name.equalsIgnoreCase(p.getName());
            }
        }
        return false;
    }
}
